/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.huawei.spare.part.replace.views.prepare.project;

import com.huawei.spare.part.replace.Constants;
import com.huawei.spare.part.replace.framework.SmartDataBus;
import com.huawei.spare.part.replace.framework.SmartRouter;
import com.huawei.spare.part.replace.models.Project;
import com.huawei.spare.part.replace.models.Switch;
import com.huawei.spare.part.replace.utils.Application;
import com.huawei.spare.part.replace.utils.JsonMapper;
import com.huawei.spare.part.replace.views.widgets.toast.Toast;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.stage.FileChooser;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @author Woo
 */
public class ProjectPresenter extends ProjectBasePresenter {

    @Override
    public void initialize() {
        SmartRouter.get().nextStepButton().setDisable(true);
        Platform.runLater(() -> {
            final Project project = SmartDataBus.get().getProject();
            renderProjectContent(project);
        });
    }


    @FXML
    private void saveProject(ActionEvent event) {
        final Project project = SmartDataBus.get().getProject();
        FileChooser chooser = new FileChooser();
        chooser.setTitle(getString("project.save.chooser.title"));
        final File projectFolder = Application.getProject(project.getProjectId());
        chooser.setInitialDirectory(projectFolder);

        // [单板类型]-[现网版本号]-[备件版本号]-[日期].xml
        final Switch switch0 = project.getSwitch0();
        String fileName = String.format("%s-%s-%s-%s", switch0.getBoardType(),
                project.getDefective().getSoftwareVersion(), project.getSpare().getSoftwareVersion(),
                DateFormatUtils.format(new Date(), "yyyyMMdd"));
        chooser.setInitialFileName(fileName);
        chooser.getExtensionFilters().add(new FileChooser.ExtensionFilter(getString("project.save.chooser.desc"), "*.json"));
        File file = chooser.showSaveDialog(SmartDataBus.get().getStage());
        if (file != null) {
            try {
                SmartDataBus.get().getProject().setSaveTo(file);
                final String content = JsonMapper.nonEmptyMapper().toJson(project);
                FileUtils.write(file, content, Constants.UTF8);
                SmartRouter.get().nextStepButton().setDisable(false);

                Toast.of(root(), getString("project.save.succeed")).show();
            } catch (IOException e) {
                Toast.of(root(), getString("project.save.failed")).show();
            }
        }
    }

}
